# -*- coding:utf-8 -*-
import MySQLdb, json
import os, time
os.sys.path.append('../../utils/constants/')
from constants import *

class commentDao(object):
    "comment: let me tell u sth about storage-visiting"
    def __init__(self, dbconfig, db_conn):
        self.__db_thread_id_keyname = dbconfig['thread_id_keyname']
        self.__db_thread_table      = dbconfig['thread_table']
        self.__db_comment_id_table  = dbconfig['comment_id_table']
        self.__db_comment_table     = dbconfig['comment_table']
        self.__list_size = 10
        self.__comment_output_list  = ['comment_id', 'thread_id', 'status', 'age', 'sex', 'phone_type', \
                'comment_uid', 'comment_uname', 'creat_time', 'uip', 'ding_count', 'content', ]
        self.__db_conn     = db_conn

    def ding_comment(self, ding_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        # 检查合法性
        if not ding_item.has_key('thread_id') or not ding_item.has_key('comment_id'):
            ret['retcode'] = E_KEY_NOT_EXIST
            ret['message'] = "ding_item field [%s] or [%s] not exist" % ('thread_id', 'comment_id', )
            return ret
        # -1- 更新thread-comment的ding计数，锁表控制并发??
        strSQL  = 'SET AUTOCOMMIT=0;'
        strSQL += ' SELECT ding_count FROM %s WHERE thread_id=%u and comment_id = %u FOR UPDATE;' \
                % (self.__db_comment_table, ding_item['thread_id'], ding_item['comment_id'], )
        strSQL += ' UPDATE %s SET ding_count = ding_count+1 WHERE thread_id=%u and comment_id = %u;' \
                % (self.__db_comment_table, ding_item['thread_id'], ding_item['comment_id'], )
        strSQL += ' COMMIT; SET AUTOCOMMIT=1;'
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret

    def add_comment(self, comment_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        #tt = time.time()*1000000
        # 检查合法性
        key_list = ['thread_id', 'comment_uid', 'age', 'sex', 'phone_type', 'comment_uname', 'creat_time', 'uip', 'content',]
        for key in key_list:
            if not comment_item.has_key(key):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = "comment_item field [%s] not exist" % (key, )
                return ret
        # -1- 插入thread的comment_id表，获得自增comment_id
        field_list = 'comment_uid'
        value = '%u' % (comment_item['comment_uid'],)
        strSQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self.__db_comment_id_table, field_list, value,)
        #print strSQL
        self.__db_conn.execute(strSQL)
        comment_id = self.__db_conn._db.insert_id()
        #print "timecost_0:", time.time()*1000000 - tt
        #tt = time.time()*1000000

        # -2- 插入thread对应的comment表
        field_list = 'thread_id, comment_id, uip, age, sex, phone_type, creat_time, comment_uid, comment_uname, content'
        conn = self.__db_conn._db
        value = '%u, %u, "%s", %u, %u, "%s", %u, %u, "%s", "%s"' % (\
                comment_item['thread_id'], \
                comment_id, \
                conn.escape_string(comment_item['uip']), \
                comment_item['age'], \
                comment_item['sex'], \
                conn.escape_string(comment_item['phone_type']),\
                comment_item['creat_time'], \
                comment_item['comment_uid'],\
                conn.escape_string(comment_item['comment_uname']),\
                conn.escape_string(comment_item['content'].replace('%', '％')), )
        strSQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self.__db_comment_table, field_list, value,)
        self.__db_conn.execute(strSQL)
        #print "timecost_1:", time.time()*1000000 - tt
        #tt = time.time()*1000000
        # -3- 更新thread的comment计数，锁表控制并发??
        strSQL  = 'SET AUTOCOMMIT=0;'
        strSQL += ' SELECT comm_count FROM %s WHERE %s=%u FOR UPDATE;' % \
                (self.__db_thread_table, self.__db_thread_id_keyname, comment_item['thread_id'],)
        strSQL += ' UPDATE %s SET comm_count = comm_count+1 WHERE %s=%u;' % \
                (self.__db_thread_table, self.__db_thread_id_keyname, comment_item['thread_id'], )
        strSQL += ' COMMIT; SET AUTOCOMMIT=1;'
        self.__db_conn.execute(strSQL)
        #print "timecost_2:", time.time()*1000000 - tt
        #tt = time.time()*1000000
        return ret

    def get_comment(self, thread_id, pageno):
        select_list = self.__comment_output_list
        select_key_string = ', '.join(select_list)
        strSQL = 'SELECT %s FROM %s WHERE thread_id = %u ORDER BY comment_id ASC limit %u, %u;' %\
                (select_key_string, self.__db_comment_table, thread_id, pageno*self.__list_size, self.__list_size)
        #print strSQL
        return self.__db_conn.query(strSQL)

    def del_comment(self, comment_item,):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        # 检查合法性
        key_list = ['thread_id', 'comment_id', 'status',]
        for key in key_list:
            if not comment_item.has_key(key):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = "comment_item field [%s] not exist" % (key, )
                return ret
        # -1- 更新thread的comment对应的标记位
        strSQL = 'UPDATE %s SET status = %u WHERE thread_id=%u and comment_id = %u;' \
                % (self.__db_comment_table, comment_item['status'], comment_item['thread_id'], comment_item['comment_id'], )
        self.__db_conn.execute(strSQL)
        return ret
